package com.wys.utils;

import cn.hutool.db.sql.Condition;
import cn.hutool.db.sql.ConditionBuilder;
import com.wys.spring.db.ConditionX;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;

import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@NoArgsConstructor
public class ConditionUtils {

    private static final List<Condition> conditions = new CopyOnWriteArrayList<>();

    public static final ConditionUtils INSTANCE = new ConditionUtils();

    public ConditionUtils addCondition(String filedName, String operator, Object value) {
        return addCondition(true, filedName, operator, value, null);
    }

    public ConditionUtils addCondition(Boolean b, String filedName, String operator, Object value) {
        return addCondition(b, filedName, operator, value, null);
    }

    public ConditionUtils addCondition(ConditionX.Builder... c) {
        for (ConditionX.Builder builder : c) {
            addCondition(builder.getFiled(), builder.getOperator(), builder.getValue());
        }
        return INSTANCE;
    }

    /**
     * @param b         判断条件为true表示执行，false：不执行
     * @param filedName 数据库表字段名称
     * @param operator  操作符号如 =,<=,!=
     * @param value     值 字符串值用 \'张三\'
     * @param lastValue 最后一个值用于 bettwen and
     * @return
     */
    public ConditionUtils addCondition(Boolean b, String filedName, String operator, Object value, Object lastValue) {
        Condition condition = new Condition(false);
        condition.setField(filedName);
        condition.setOperator(operator);
        condition.setValue(value);
        condition.setSecondValue(lastValue);
        if (b) {
            conditions.add(condition);
        }
        return new ConditionUtils();
    }

    public static String buildSql() {
        String sql = ConditionBuilder.of(conditions.toArray(new Condition[0])).build();
        if (ObjectUtils.isNotEmpty(conditions)) sql = " where " + sql;
        conditions.clear();
        return sql;
    }

//    public static void main(String[] args) {
//        ConditionUtils.INSTANCE.addCondition(true,"userId", "=", "sss", null).addCondition("phone", "=", "'"+"1866414242512"+"'");
//        System.out.println(ConditionUtils.buildSql());
//        ConditionUtils.INSTANCE.addCondition(true,"userName","=","张三",null).addCondition("age","=","18");
//        System.out.println(ConditionUtils.buildSql());
//    }

}
